//
//  WmcManualInviteTeamMemeberVC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/14.
//

import RxSwift
import SVProgressHUD
import UIKit

// MARK: - 扩展WmcManualInviteTeamMemeberVC + WmcNavigatorProtocol

extension WmcManualInviteTeamMemeberVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.manualInviteTeamMember]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vc = WmcManualInviteTeamMemeberVC()
        if let teamAblum = parms.context as? WmcMediaTeamAlbumModel {
            let vm = WmcManualInviteTeamMemeberVM()
            vm.teamAblum = teamAblum
            vc = WmcManualInviteTeamMemeberVC(vm)
        }
        return vc
    }
}

// MARK: - 扩展WmcManualInviteTeamMemeberVC + WmcVMProtocol

extension WmcManualInviteTeamMemeberVC: WmcVMProtocol {
    typealias VMType = WmcManualInviteTeamMemeberVM
}

/// 手动邀请
class WmcManualInviteTeamMemeberVC: WmcBaseVC {
    private var clickedCount: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func makeUI() {
        title = "手动添加"
        makeNavView(showShadow: false)

        // view.addSubview(noteLabel)
        view.addSubview(nameView)
        view.addSubview(phoneView)
        view.addSubview(addButton)

//        noteLabel.snp.makeConstraints { make in
//            make.top.equalTo(navView.snp.bottom)
//            make.left.right.equalToSuperview()
//            make.height.equalTo(32)
//        }

        nameView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(16)
            make.left.right.equalToSuperview()
        }

        phoneView.snp.makeConstraints { make in
            make.top.equalTo(nameView.snp.bottom).offset(16)
            make.left.right.equalToSuperview()
        }

        addButton.snp.makeConstraints { make in
            make.top.equalTo(phoneView.snp.bottom).offset(56)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(44)
        }

        nameView.inputTextfield.becomeFirstResponder()
    }

    override func bindViewModel() {
        /// 限制输入字符最多15个数
        nameView.inputTextfield.limitInputCharactersCount(count: 15)
        /// 手机号限制输入 11 位
        phoneView.inputTextfield.limitInputCharactersCount(count: 11)

        let remarkValid = nameView.inputTextfield.rx.text.map { ($0 ?? "").count > 0 }
        let phoneValid = phoneView.inputTextfield.rx.text.map { ($0 ?? "").count > 0 }

        let inputValid = Observable.combineLatest(remarkValid, phoneValid).map { $0 && $1 }

        inputValid.bind(to: addButton.rx.isEnabled).disposed(by: rx.disposeBag)
        inputValid.map(transform(valid:)).bind(to: addButton.rx.backgroundColor).disposed(by: rx.disposeBag)
    }

    override func bindViewAction() {
        addButton.rx.controlEvent(.touchUpInside).debounce(.seconds(Int(0.5)), scheduler: MainScheduler.instance).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            let mobile = weakSelf.phoneView.inputTextfield.text ?? ""
            let remark = weakSelf.nameView.inputTextfield.text ?? ""

            if !weakSelf.isPhoneNumber(phoneNumber: mobile) {
                WmcHudManager.toast("请输入正确的手机号")
            } else if remark == "" {
                WmcHudManager.toast("请输入备注")
            }

            if weakSelf.isPhoneNumber(phoneNumber: mobile) && (remark != "") {
                /// 需要弹窗
                SVProgressHUD.show()
                weakSelf.viewModel.addTeamMember(mobile: mobile, remark: remark) { _ in
                    WmcHudManager.toast("添加成功")
                    weakSelf.popToSpecificVC(vcClass: WmcTeamCloudAlbumMembersVC.self)
                    /// 通知刷新
                    WmcNotificationManager.shared.post(type: .addTeamMemberSucceed, object: nil)
                    SVProgressHUD.dismiss()
                } failure: { error in
                    if error.localizedDescription == "用户已经加入该团队" {
                        WmcManualAddTeamMemberAlert.alertView(title: "温馨提示", content: "用户已经加入该团队", btnTitle: "确定", confirmB: {
                            // do nothing
                        }).show()

                        weakSelf.clickedCount = weakSelf.clickedCount + 1
                    }
                    SVProgressHUD.dismiss()
                }
            }

        }.disposed(by: rx.disposeBag)
    }

    func transform(valid: Bool) -> UIColor {
        if valid {
            return UIColor.wmc_mainTheme
        } else {
            return UIColor.wmc_grayH14_CCCCCC
        }
    }

    lazy var noteLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.wmc_blue_5290FD
        view.backgroundColor = UIColor.wmc_blue_477EFF
        view.text = "添加的成员将收到免费的短信通知"
        view.textAlignment = .center
        view.font = 14.yp.uiFont
        return view
    }()

    lazy var nameView: WmcInputItemView = {
        let view = WmcInputItemView()
        view.leftTitle = "备注"
        view.placeholder = "请输入备注"
        return view
    }()

    lazy var phoneView: WmcInputItemView = {
        let view = WmcInputItemView()
        view.leftTitle = "手机号码"
        view.placeholder = "请输入11位手机号"
        view.inputTextfield.keyboardType = .numberPad
        return view
    }()

    lazy var addButton: WmcNormalButton = {
        let view = WmcNormalButton()
        view.backgroundColor = UIColor.wmc_mainTheme
        view.font = 16.yp.uiFont(weight: .semibold)
        view.textColor = UIColor.wmc_white_FFFFFF
        view.title = "添加"
        view.textAlignment = .center
        view.layer.cornerRadius = 4
        view.clipsToBounds = true
        return view
    }()
}

extension WmcManualInviteTeamMemeberVC {
    /// 检查手机号有效性
    /// - Parameter phoneNumber: phoneNumber description
    /// - Returns: description
    func isPhoneNumber(phoneNumber: String) -> Bool {
        if phoneNumber.count == 0 {
            return false
        }
        let mobile = "^1[3-9]\\d{9}$"
        let regexMobile = NSPredicate(format: "SELF MATCHES %@", mobile)
        if regexMobile.evaluate(with: phoneNumber) == true {
            return true
        } else {
            return false
        }
    }
}

extension WmcManualInviteTeamMemeberVC {}
